# coding:utf-8
import datetime

import requests
import pprint
from scrapy import Selector
import sys
import re


def get_td_data(query):
    result = list()
    url = "https://tdtd.vip/local/games"
    headers = {
        'Referer': 'https://tdtd.vip/index',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0'
    }
    params = {
        'query': query,
        'pagenum': '1',
        'pagesize': '18',
        'sortitem': 'createtime',
        'ishow': False,
    }

    res = requests.get(url=url, params=params)
    data = res.json()
    for d in data['data']:
        url = "https://tdtd.vip/game/" + d['_id']
        create_time = datetime.datetime.fromtimestamp(d['createtime'] / 1000).strftime('%Y-%m-%d %H:%M:%S')
        result.append({
            'origin': 'tdtd.vip',
            'name': d['Cname'],
            'url': url,
            'image_url': d['cover'],
            'categories': d['categories'],
            'create_time': create_time
        })

    return result


def get_game520_data(query):
    url = "https://www.gamer520.com/"

    headers = {
        'Referer': 'https://www.gamer520.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0'
    }

    result = list()

    params = {
        's': query
    }

    res = requests.get(url=url, params=params)
    selector = Selector(text=res.text)
    content = selector.xpath('//article')
    for c in content:
        # c = c.replace("\n", "").replace("\r", "")
        url = c.css(".placeholder a::attr(href)").get()
        image = c.css(".placeholder a img::attr(data-src)").get()
        title = c.css(".placeholder a img::attr(alt)").get()
        categories = c.css(".meta-category a::text").getall()
        categories = [i.replace("\n", "").replace("\r", "").strip() for i in categories]
        categories = [i for i in categories if i != '']
        create_time = c.css(".meta-date time::text").get()
        # print(c)
        # media = re.findall('<div class="placeholder" .*?>(.*?)</div>', c)[0]
        # wrapper = re.findall('<div class="entry-wrapper">(.*)</div>', c)[0]
        # url = re.findall('<a href="(.*?)">', media)[0]
        # title = re.findall('alt="(.*?)"', media)[0]
        # image = re.findall('data-src="(.*?)"', media)[0]
        # categories = re.findall('<i .*</i>(.*?)</a>', wrapper)
        # create_time = re.findall('<time .*</i>(.*?)</time>', wrapper)[0]
        result.append({
            'origin': 'gamer520',
            'name': title,
            'url': url,
            'image_url': image,
            'categories': categories,
            'create_time': create_time
        })
    return result


def game_main(query=''):
    result1 = get_td_data(query)
    result2 = get_game520_data(query)
    return result1 + result2


def add(a, b):
    return a + b


if __name__ == '__main__':
    query = sys.argv[1]
    result = game_main(query=query)
    for r in result:
        pprint.pprint(r)
